Online-Academy
Look, Read, Understand, Apply

String and StringBuffer

String and StringBuffer

In Java, String and StringBuffer are both used to work with text, but the major difference is that String is immutable, while StringBuffer is mutable.

String

A String object cannot be changed after it is created. Any operation that appears to modify a string actually creates a new String object.

String s = "Hello";
s = s + " World";
System.out.println(s);

Here, "Hello" is not modified. A new String "Hello World" is created.

Common String Methods

MethodPurposeExample
length()Returns number of characterss.length()
charAt() Returns character at index s.charAt(0)
concat() Joins stringss.concat(" World")
equals() Compares contentss.equals("Hello")
equalsIgnoreCase() Compares ignoring cases.equalsIgnoreCase("hello")
substring() Extracts part of strings.substring(1, 4)
toUpperCase() Converts to uppercases.toUpperCase()
toLowerCase() Converts to lowercases.toLowerCase()
indexOf() Finds positions.indexOf("l")
replace() Replaces characters/texts.replace('l', 'x')
trim() Removes leading/trailing spacess.trim()
contains() Checks whether text existss.contains("ell")

Example

String s = "Hello";

System.out.println(s.length());          // 5
System.out.println(s.charAt(1));         // e
System.out.println(s.toUpperCase());     // HELLO
System.out.println(s.substring(1, 4));   // ell
System.out.println(s.indexOf('l'));      // 2
System.out.println(s.replace('l', 'x')); // Hexxo

String Buffer

StringBuffer represents a modifiable sequence of characters.

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);  

Important StringBuffer methods

Method Purpose Example
append() Adds text at the end sb.append(" Java")
insert() Inserts text at a position sb.insert(5, " Java")
delete() Deletes characters sb.delete(5, 10)
deleteCharAt() Deletes one character sb.deleteCharAt(2)
replace() Replaces part of text sb.replace(0, 5, "Hi")
reverse() Reverses the sequence sb.reverse()
charAt() Gets character sb.charAt(0)
setCharAt() Changes a character sb.setCharAt(0, 'J')
length() Returns length sb.length()
capacity() Returns current capacity sb.capacity()
substring() Returns part as String sb.substring(1, 4)
toString() Converts to String sb.toString()
StringBuffer sb = new StringBuffer("Hello");

sb.append(" Java");
System.out.println(sb);           // Hello Java

sb.insert(5, " World");
System.out.println(sb);           // Hello  World Java

sb.delete(5, 11);
System.out.println(sb);           // Hello Java

sb.setCharAt(0, 'Y');
System.out.println(sb);           // Yello Java

sb.reverse();
System.out.println(sb);           // avaJ olleY